#include "common.h"
#include "decodedict.h"

bool findPasswordDict(const char *password, char *filename, char  *line)
{
	bool ret = false;
	char cmd[1024] = {0};
	sprintf(cmd, "grep  -rni '%s' %s ",  password, DICT_PATH_DIR);
	FILE *pp = popen(cmd,  "r");
	if (!pp) {
		return ret;
	}
	char tmp[1024] = {0};
	while (fgets(tmp, sizeof(tmp),  pp) != NULL) {
		if (tmp[strlen(tmp) - 1] == '\n') {
			tmp[strlen(tmp) - 1] = '\0'; //去除换行符
		}
	}

	const char* delim=":";//分隔符字符串
	char* p=strtok(tmp, delim);//第一次调用strtok
	int i = 0;
	while (p!=NULL){//当返回值不为NULL时，继续循环
		if (i == 0) {
			sprintf(filename, "%s", p);//输出分解的字符串
		}
		if (i == 1) {
			sprintf(line, "%s", p);//输出分解的字符串
			ret = true;
		}
		p = strtok(NULL,delim);//继续调用strtok，分解剩下的字符串
		++i;
	}

	pclose(pp); //关闭管道
	return ret;
}

bool getPasswordDict(const char *password, char *src_password, char *filename, char *line )
{
	bool ret = false;
    char cmd[1024] = {0};
    sprintf(cmd, "sed  -n '%sp'  %s ",  line, filename);
    FILE *pp = popen(cmd,  "r");
    if (!pp) {
        return ret;
    }
    char tmp[1024] = {0};
    while (fgets(tmp, sizeof(tmp),  pp) != NULL) {
        if (tmp[strlen(tmp) - 1] == '\n') {
            tmp[strlen(tmp) - 1] = '\0'; //去除换行符
        }
    }

    const char* delim="=";//分隔符字符串
    char* p=strtok(tmp, delim);//第一次调用strtok
    int i = 0;
    while (p!=NULL){//当返回值不为NULL时，继续循环
    	if (i == 0) {
    		sprintf(src_password, "%s", p);//输出分解的字符串
    	}
    	if (i==1) {
    		if (strcmp(password, p) ==0)
    			ret = true;
    	}
        p = strtok(NULL,delim);//继续调用strtok，分解剩下的字符串
        ++i;
    }
    pclose(pp); //关闭管道
    return ret;
}

void  decondeDict(void)
{
	char password[100]={0};
	char src_password[100]={0};
	char filename[256] = {0};
	char line[30] = {0};
	bool ret;
	std::cout <<"请输密文：";
	scanf("%s",  password);
	std::cout <<"正在解密.................."<<std::endl;

	FILE *fp = NULL;
	fp =  fopen(DICT_PATH_DIR, "r");

	if (!fp) {
		goto DECODE_DICT_ERROR;
	}

	ret = findPasswordDict(password, filename, line);
	if (!ret) {
		goto DECODE_DICT_ERROR;
	}

	ret = getPasswordDict(password, src_password, filename, line);
	if (!ret) {
		goto DECODE_DICT_ERROR;
	}
	printf("破解成功，原始密码为：%s", src_password);

DECODE_DICT_ERROR:
	std::cout <<"破解失败，密码字典无法解析"<<std::endl;
	return;
}

